package com.fys.markbook.util

import com.mchange.v2.c3p0.ComboPooledDataSource
import java.beans.PropertyVetoException
import java.sql.Connection
import java.util.*

/**
 * @Title:
 * @Description:
 * @Author: fanyushuai
 * @Date: 2023/9/26 0:11
 * @Version V1.0
 */
object C3P0DataSourceFactory {

    private var driverName: String? = null
    private var url: String? = null
    private var userName: String? = null
    private var password: String? = null

    // 使用静态代码块的方式，使得数据库的连接信息在工具类加载的时候就获取并赋值
    init {
        try { //第二步：定义数据库连接信息
            val properties = JDBCUtil::class.java.getClassLoader().getResourceAsStream("database.properties")
            //使用Properties类来读取属性文件中对应的值
            val prop = Properties()
            //把输入流中的信息加载到Properties的对象
            prop.load(properties)
            driverName = prop.getProperty("driverName")
            url = prop.getProperty("url")
            userName = prop.getProperty("username")
            password = prop.getProperty("password")
            //获取数据库的连接
            //第一步：加载数据库驱动
            Class.forName(driverName)
        } catch (e: Exception) {
            println("初始化数据库错误：")
            e.printStackTrace()
        }
    }
    @Throws(PropertyVetoException::class)
    fun createDataSource(): ComboPooledDataSource {
        val dataSource = ComboPooledDataSource()
        dataSource.jdbcUrl = url
        dataSource.user =userName
        dataSource.password = password
        dataSource.driverClass = driverName
        // 初始连接池大小
        dataSource.initialPoolSize = 5
        // 最小连接池大小
        dataSource.minPoolSize = 5
        // 最大连接池大小
        dataSource.maxPoolSize = 20
        // 最大空闲时间
        dataSource.maxIdleTime = 300
        return dataSource
    }
}
